//
//  ST_PairsLoveViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwifterSwift
import SwiftyJSON

/**
 未读 喜欢数
 */
var UNREAD_PAIRS_LOVE_NUMBER = 0


//喜欢index-Controller 【弃用】
class ST_PairsLoveViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = Color.white
        
        
        view.addSubview(personal_sub_label)
        personal_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(15)
        }
        
        
        view.addSubview(unlike_btn)
        view.addSubview(like_btn)
        
        let offSet = 10
        
        unlike_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(80)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-49-16)
            make.right.equalTo(view.snp.centerX).offset(-offSet)
        }
        
        like_btn.snp.makeConstraints { (make) in
            make.bottom.width.height.equalTo(unlike_btn)
            make.left.equalTo(view.snp.centerX).offset(offSet)
        }
        
        
        view.addSubview(filter_btn)
        filter_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(17)
            make.width.height.equalTo(30)
            make.centerY.equalTo(like_btn)
        }
        
        view.addSubview(refuseBtn)
        refuseBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-17)
            make.width.height.equalTo(30)
            make.centerY.equalTo(like_btn)
        }
        
        
        view.addSubview(koloda_view)
        koloda_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalTo(unlike_btn.snp.top).offset(-10)
            make.top.equalTo(personal_sub_label.snp.bottom).offset(18)
        }
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(emptyView.figured_height)
            make.centerY.equalToSuperview().offset( iPhoneXSeries ? -70 : -80)
        }
        
        koloda_view.backgroundCardsTopMargin = 0
        
        koloda_view.delegate = self
        koloda_view.dataSource = self
        
        
        
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.received_love, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.ban_somebody, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.refresh_pairs_love_controller, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.network_reachability_status, object: nil)
        
        request_data()
    }
    
    @objc func refresh_data(){
        
        self.currentPage = 0
        self.data_array.removeAll()
        self.koloda_view.reloadData()
        self.request_data()
    }
    
    @objc func clear_data(){
        currentPage = 0
        self.data_array.removeAll()
        self.koloda_view.reloadData()
    }
   
    
//    MARK: - View  DataSet
    fileprivate var currentPage = 0
    
    
    fileprivate var lastPlayView:ST_PairsLoveItemView?
    
    fileprivate var currentView:ST_PairsLoveItemView?{
        get{
            
            if let item = koloda_view.viewForCard(at: koloda_view.currentCardIndex) as? ST_PairsLoveItemView{
                return item
            }
            return nil
        }
    }
    
    var previous_direction_array = [SwipeResultDirection]()
    
    fileprivate var curr_filter = ST_PairsLoveFilterModel()
    
    fileprivate var data_array = [ST_PairsLoveItemViewModel]()
    
    fileprivate var currentPageCount = 0
    
    fileprivate func request_data(){
        
        self.koloda_view.isUserInteractionEnabled = false
        
        currentPage += 1
        
        let param = ["page":currentPage,
                    "size":20,
                    "age_end":curr_filter.age_end,
                    "age_start":curr_filter.age_start,
                    "have_feature":curr_filter.have_feature,
                    "have_like_feature":curr_filter.have_like_feature] as [String : Any]
        
        
        JVrequest(PH.likeIndexApi,parameters:param, success: { (json) in
            
            let data = json["data"]
            
            print("喜欢首页数据：",data)
            
            var array = [ST_PairsLoveItemViewModel]()
            
            for item in data["list"].arrayValue{
                
                if let model = ST_PairsLoveItemViewModel.deserialize(from: item.dictionaryObject){
                    
                    let albumList = ST_PairsShareParticularModel.describe(json_array: item["album"].arrayValue)
                    
                    model.album = albumList
                    
                    array.append(model)
                }
            }
            
            self.currentPageCount = array.count
            
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.previous_direction_array.removeAll()
            self.koloda_view.resetCurrentCardIndex()
            
//            self.koloda_view.reloadData()
             
            self.emptyView.isHidden = self.data_array.count > 0
            self.koloda_view.isHidden = self.data_array.count < 1
            self.personal_sub_label.isHidden = self.data_array.count < 1
            self.like_btn.isHidden = self.koloda_view.isHidden
            self.unlike_btn.isHidden = self.koloda_view.isHidden
            
            if self.currentPage == 1{

                UNREAD_PAIRS_LOVE_NUMBER = data["count"].intValue
                
                ST_BTLaunchController.shared.setting_unread_msg_count()
            }
            
            self.koloda_view.isUserInteractionEnabled = true
            
        }) { (code, err) in
            
            self.koloda_view.isUserInteractionEnabled = true
            
            self.emptyView.isHidden = self.data_array.count > 0
            self.koloda_view.isHidden = self.data_array.count < 1
            self.personal_sub_label.isHidden = self.data_array.count < 1
            self.like_btn.isHidden = self.koloda_view.isHidden
            self.unlike_btn.isHidden = self.koloda_view.isHidden
            
            ToastHud(text: err, view: self.view)
        }
    }
    

//    MARK: - Properties
    fileprivate lazy var koloda_view: KolodaView = {
        let control = KolodaView()
        return control
    }()
    
    
    
    fileprivate lazy var emptyView:ST_BTEmptyView = {
        
        let control = ST_BTEmptyView.init(title: "没人喜欢你？快添加特质啊！", imageName: ST_ImageUtils.imageName("喜欢_img_喜欢(空)")!, btnTitle: "添加特质") {
            
            push_to_push_peculiarity_controller(navigationController: self.navigationController)
        }
        control.isHidden = true
        return control
    }()
    
    
    fileprivate lazy var personal_sub_label:UILabel = {
        let control = UILabel()
        return control
    }()
    
    
    fileprivate lazy var unlike_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_不喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(unlike_handle))
        return control
    }()
    
    fileprivate lazy var like_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(like_handle))
        return control
    }()
    
    
    fileprivate lazy var filter_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_筛选")!)
        control.addTarget(self, action: #selector(filter_gender_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var refuseBtn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("喜欢_icon_拒绝历史")!)
        control.addTarget(self, action: #selector(push_refuse_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
}

//MARK:- Event
extension ST_PairsLoveViewController{
    
    @objc func push_refuse_handle(){
        
        self.navigationController?.pushViewController(ST_IgnoreLoveViewController())
        
    }
    
    @objc func filter_gender_handle(sender:UIButton){
    }
    
    @objc func unlike_handle(){
        
        koloda_view.swipe(SwipeResultDirection.left)
        
    }
    @objc func like_handle(){
        
        koloda_view.swipe(SwipeResultDirection.right)
        
    }
}

//MARK:- Notification observer
extension ST_PairsLoveViewController{
    
    @objc func register_finish_handle(){
        
        currentPage = 0
        
        request_data()
        
    }
    
}
//MARK:- KolodaView Delegate
extension ST_PairsLoveViewController:KolodaViewDelegate,KolodaViewDataSource{
    
    
    func kolodaDidRunOutOfCards(_ koloda: KolodaView) {
        
        if self.currentPageCount < 20{
            return
        }
        
        currentPage += 1
        self.data_array.removeAll()
        request_data()
        
    }
    
    func koloda(_ koloda: KolodaView, didSwipeCardAt index: Int, in direction: SwipeResultDirection) {
        
        
        

        guard let currentModel = self.data_array[safe:index],let albumFirst = currentModel.album.first else {
            
            lastPlayView?.stop()
            
            UNREAD_PAIRS_LOVE_NUMBER -= 1
            
            ST_BTLaunchController.shared.setting_unread_msg_count()
            
            return
        }
        
        self.previous_direction_array.append(direction)
        
        
        let info_model = ST_MatchUserInfo.init(accid: currentModel.accid, avatar: albumFirst.imageUrl, nickname: currentModel.nickname)
            
//       喜欢接口调用
        if direction == .right || direction == .topRight || direction == .bottomRight {
            
//            likeBehavior(info: info_model, isLike: true, loveSquare: true)
            likeBehavior(info: info_model, isLike: true, loveSquare: true,refreshloveIndex:false, loveWay: ST_LoveWay.recommend, peculiarity: "", responseClosure: { (f) in
                
                print("滑过Index:",index)
                //                最后一个
                if self.data_array.count == index + 1{
                    self.emptyView.isHidden = false
                    self.koloda_view.isHidden = true
                    self.personal_sub_label.isHidden = true
                    self.like_btn.isHidden = self.koloda_view.isHidden
                    self.unlike_btn.isHidden = self.koloda_view.isHidden
                }
                
            }) {
             
                if let direction = self.previous_direction_array.last{
                
                    self.previous_direction_array.removeLast()
                    main_thread_execute(afterDelay: 1) {
                        self.koloda_view.revert_action(direction: direction)
                    }
                    
                    UNREAD_PAIRS_LOVE_NUMBER += 1
                    
                    ST_BTLaunchController.shared.setting_unread_msg_count()
                }
            }
            
        }
//       不喜欢接口调用
        else{
//             likeBehavior(info: info_model, isLike: false, loveSquare: true)
            
            likeBehavior(info: info_model, isLike: false, loveSquare: true,refreshloveIndex:false, loveWay: ST_LoveWay.recommend, peculiarity: "", responseClosure: { (f) in
                
               print("不喜欢滑过Index:",index)
                //                最后一个
                  if self.data_array.count == index + 1{
                      self.emptyView.isHidden = false
                      self.koloda_view.isHidden = true
                      self.personal_sub_label.isHidden = true
                      self.like_btn.isHidden = self.koloda_view.isHidden
                      self.unlike_btn.isHidden = self.koloda_view.isHidden
                  }
                
            }) {
             
                
                if let direction = self.previous_direction_array.last{
                
                    self.previous_direction_array.removeLast()
                
                    main_thread_execute(afterDelay: 1) {
                        self.koloda_view.revert_action(direction: direction)
                    }
                    
                    UNREAD_PAIRS_LOVE_NUMBER += 1
                    
                    ST_BTLaunchController.shared.setting_unread_msg_count()
                }
            }
            
        }
        
        
        UNREAD_PAIRS_LOVE_NUMBER -= 1
        
        ST_BTLaunchController.shared.setting_unread_msg_count()
        
    }
    
    func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
        
        let itemView = ST_PairsLoveItemView()
        if let model = data_array[safe:index]{
            itemView.bind_view_data_set(model: model)
        }
        return itemView
    }
    
    func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
        
        guard let model = data_array[safe:index] else{
            return
        }
        
        
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = model.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
    
    
    func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
        return data_array.count
    }
    
    func koloda(_ koloda: KolodaView, didShowCardAt index: Int) {
    
        lastPlayView?.stop()
    
        self.currentView?.play()
        
        
        if let model = data_array[safe:index]{
            
            var str = "他"
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == ST_SEX.male{
                str = "她"
            }
            
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
            
            if model.send_way == 1{
                str += "从推荐喜欢了你哦！"
                let attrString = NSMutableAttributedString(string: str)
                
                attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                
                personal_sub_label.attributedText = attrString
                
            }else if model.send_way == 2{
                str += "喜欢你 " + model.feature_name + " 的特质哦！"
                
                let attrString = NSMutableAttributedString(string: str)
                
                attrString.addAttributes(attr, range: NSRange(location: 0, length: 5))
                
                let attr2: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 1, green: 0.76, blue: 0.03, alpha: 1)]
                
                attrString.addAttributes(attr2, range: NSRange(location: 5, length: model.feature_name.count))
                
                attrString.addAttributes(attr, range: NSRange(location: 5+model.feature_name.count, length: 6))
                
                personal_sub_label.attributedText = attrString
            }else{
                personal_sub_label.attributedText = NSAttributedString()
            }
            
        }
        
    }
    
    func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> KolodaOverlayView? {
        return ST_SampleOverLayView()
        
    }
}


//MARK: -
private let overlayCorner = 15.cgFloat

class ST_SampleOverLayView: KolodaOverlayView {


    private let overlay_right_image_name = "homePage_喜欢"
    private let overlay_left_image_name = "homePage_不喜欢"
    
    lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(25)
        }
        
        self.cornerRadius = overlayCorner
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var overlayState: SwipeResultDirection? {
        didSet {
            switch overlayState {
            case .left?,.topLeft,.bottomLeft :
                cover_image_view.image = UIImage(named: overlay_left_image_name)
                cover_image_view.snp.remakeConstraints { (make) in
                    make.right.equalToSuperview().offset(-25)
                    make.centerY.equalToSuperview()
                }
                        
                self.backgroundColor = UIColor.init(hex: 0x6BDA99, transparency: 0.8)
                
            case .right?,.topRight,.bottomRight :
                
                cover_image_view.image = UIImage(named: overlay_right_image_name)
                
                cover_image_view.snp.remakeConstraints { (make) in
                    make.left.equalToSuperview().offset(25)
                    make.centerY.equalToSuperview()
                }
//                107    154    65
                self.backgroundColor = UIColor.init(hex: 0xE14356, transparency: 0.8)
                
            default:
                self.backgroundColor = UIColor.clear
                break
            }
        }
    }
    
}
